<template>
  <u-drawer
    v-model:visible="selfVisible"
    :title="currentTitle"
    :width="520"
    :footer-style="{display: 'flex', justifyContent: 'flex-end'}"
    :mask-closable="currentMode === 'view'"
    @after-visible-change="handleChange"
  >
    <u-spin fix :loading="spinShow" />
    <dynamics-form
      ref="formRef"
      :model="model"
      :setting="setting"
      :label-width="110"
      :disabled="currentMode === 'view'"
      tips-placement="bottom"
    >
      <template #notInRange>
        <u-time-picker
          range
          clearable
          format="HH:mm"
          v-model="model.notInRange"
        />
      </template>
    </dynamics-form>
    <template v-if="currentMode !== 'view'" #footer>
      <u-button type="default" @click="handleChange(false)">
        取消
      </u-button>
      <u-button type="primary" class="m-l-1" :loading="saveLoading" @click="handleSubmit">
        保存
      </u-button>
    </template>
  </u-drawer>
</template>
<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { message, DynamicsForm } from '@bairong/vix'
import {
  addTemplateApi,
  updateTemplateApi,
  templeteExistsApi,
  getSmsTemplateApi,
  getSmsDetailApi
} from '@api/message'
import useDrawer from '@/hooks/useDrawer'

export default {
  name: 'MEdit',
  components: { DynamicsForm },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentModel: {
      type: [Object, String],
      default: undefined
    },
    currentMode: {
      type: String,
      default: 'add',
      validator: val => ['view', 'add', 'edit'].includes(val)
    }
  },
  emits: ['update:visible', 'close', 'refreshTable'],
  setup(props, { emit }) {
    const store = useStore()
    const formRef = ref(null)
    const smsTemplates = ref([])
    const saveLoading = ref(false)
    const { selfVisible, spinShow, handleChange } = useDrawer(props, emit)

    const currentTitle = computed(() => {
      let title = ''
      switch (props.currentMode) {
        case 'view':
          title = '查看'
          break
        case 'add':
          title = '新增'
          break
        case 'edit':
          title = '编辑'
          break
        default:
          break
      }
      return `${title}短信任务模板`
    })

    const model = ref({
      templateName: '',
      apiCode: '',
      smsTemplateId: '',
      number: '',
      shortLink: '',
      remark: ''
    })

    const setting = ref([
      {
        name: 'templateName',
        label: '短信任务名称',
        type: 'input',
        props: { placeholder: '请输入短信任务名称' },
        // disabled: props.currentMode === 'edit',
        rules: [
          { required: true, message: '请输入短信任务名称', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5\dA-Za-z-_]{2,30}$/,
            message: '仅支持中英文、数字、中划线、下划线，限制2-30字符',
            trigger: 'blur'
          }
        ],
        tips: '支持中英文、数字、中划线、下划线，限制2-30字符'
      },
      {
        name: 'apiCode',
        label: '商户',
        type: 'select',
        props: { placeholder: '请选择商户', filterable: true },
        rules: [{ required: true, message: '请选择商户', trigger: 'change' }],
        options: [],
        cascade: ['smsTemplateId'],
        remoteMethod: () => new Promise(resolve => {
          store.dispatch('getCompanyOptions').then(res => {
            resolve(res)
          })
        }),
        onChange: () => {
          model.value.smsTemplateId = ''
        }
      },
      {
        name: 'smsTemplateId',
        label: '短信模板',
        type: 'select',
        props: { placeholder: '请选择短信模板' },
        options: [],
        rules: [{
          required: true, type: 'number', message: '请选择短信模板', trigger: 'change'
        }],
        cascadeMethod: () => new Promise(resolve => {
          if (model.value.apiCode) {
            const params = { apiCode: model.value.apiCode }
            getSmsTemplateApi(params).then(res => {
              smsTemplates.value = res ? res.map(r => ({ ...r, value: r.id, label: r.smsName })) : []
              resolve(smsTemplates.value)
            })
          } else {
            (
              resolve([])
            )
          }
        })
      },
      {
        name: 'number',
        label: '短信链接编号',
        type: 'input',
        props: {
          placeholder: '请输入短信链接编号',
          maxlength: 50,
          showWordLimit: true
        },
        rules: [{
          validator: (rule, value, callback) => {
            if (value && !/^\d+$/.test(value)) {
              callback(new Error('请填写数字'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      },
      {
        name: 'shortLink',
        label: '短信链接',
        type: 'input',
        props: {
          placeholder: '请输入短信链接',
          maxlength: 150,
          showWordLimit: true
        }
      },
      {
        name: 'remark',
        label: '备注',
        type: 'input',
        props: {
          type: 'textarea',
          placeholder: '请输入备注',
          maxlength: 300,
          showWordLimit: true
        }
      }
    ])

    const generateModel = tempModel => {
      const {
        templateName = '',
        apiCode = '',
        smsTemplateId = '',
        number = '',
        shortLink = '',
        remark = ''
      } = tempModel
      model.value = {
        templateName,
        apiCode: `${apiCode}`,
        smsTemplateId,
        number,
        shortLink,
        remark
      }
    }

    const generateParams = () => {
      const companys = store.getters.companyOptions
      const targetCompany = companys.find(a => a.apiCode === model.value.apiCode)
      const targetTemplates = smsTemplates.value.find(s => s.value === model.value.smsTemplateId)
      const params = {
        ...model.value
      }
      if (targetCompany) {
        params.companyId = targetCompany.companyId
        params.companyName = targetCompany.companyName
      }
      if (targetTemplates) {
        params.smsTemplateName = targetTemplates.smsName
      }
      if (props.currentMode === 'edit') {
        params.smsTaskTemplateId = typeof props.currentModel === 'string' ? props.currentModel : props.currentModel.smsTaskTemplateId
      }
      return params
    }

    const handleSubmit = () => {
      formRef.value.validate()
        .then(() => {
          saveLoading.value = true
          const smsTaskTemplateId = (typeof props.currentModel === 'string' ? props.currentModel : props.currentModel.smsTaskTemplateId) || ''
          templeteExistsApi({ templateName: model.value.templateName, id: smsTaskTemplateId }).then(res => {
            // true 可用
            if (res) {
              const params = generateParams()
              if (props.currentMode === 'add') {
                addTemplateApi(params).then(() => {
                  saveLoading.value = false
                  message.success('新增短信模板成功！')
                  emit('refreshTable', true)
                  handleChange(false)
                }).catch(err => {
                  message.error(err)
                  saveLoading.value = false
                })
              }
              if (props.currentMode === 'edit') {
                updateTemplateApi(params).then(() => {
                  message.success('编辑任务模板成功！')
                  saveLoading.value = false
                  emit('refreshTable', false)
                  handleChange(false)
                }).catch(err => {
                  message.error(err)
                  saveLoading.value = false
                })
              }
            } else {
              message.error('任务名称重复！')
              saveLoading.value = false
            }
          }).catch(err => {
            message.error(err)
            saveLoading.value = false
          })
        })
        .catch(err => {
          console.error(err)
        })
    }

    onMounted(() => {
      // 策略树编辑模版
      if (typeof props.currentModel === 'string') {
        spinShow.value = true
        getSmsDetailApi({ id: props.currentModel }).then(res => {
          generateModel(res)
          spinShow.value = false
        }).catch(err => {
          message.error(err)
          spinShow.value = false
        })
      } else if (props.currentMode !== 'add') {
        generateModel(props.currentModel)
      }
    })

    return {
      selfVisible,
      spinShow,
      saveLoading,
      handleChange,
      formRef,
      model,
      currentTitle,
      setting,
      handleSubmit
    }
  }
}
</script>
<style lang="less"></style>
